﻿using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static 出货绑定.MainViewModel;
using MessageBox = HandyControl.Controls.MessageBox;

namespace 出货绑定
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        private Db2_2 db2 = new Db2_2();
        public MainViewModel viewModel= new MainViewModel();
        private SoundPlayer playerNG = new SoundPlayer(System.Environment.CurrentDirectory + "\\ng.wav");
        private SoundPlayer playerOK = new SoundPlayer(System.Environment.CurrentDirectory + "\\ok.wav");
        public MainWindow()
        {
            InitializeComponent();
            DataContext = viewModel;
        }

        private void TextBoxCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                try
                {
                    if (viewModel.Wait[0] <= 0)
                    {
                        TextBoxCode.Focus();
                        TextBoxCode.SelectAll();
                        Growl.Warning("绑定已完成！");
                        playerNG.Play();
                        return;
                    }
                    string code = TextBoxCode.Text.Trim();
                    if (TextBoxTitle.Text == "批次号")
                    {
                        if (!code.StartsWith("@") || !code.Contains(" "))
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning("批次号有误！");
                            playerNG.Play();
                            return;
                        }
                        if (!int.TryParse(code.Replace("@", "").Split(' ')[0], out int batch))
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning("批次号有误！");
                            playerNG.Play();
                            return;
                        }
                        bool isIn = false;
                        string size = "";
                        string order ="";
                        foreach (var item in orders)
                        {
                            if (batch <= item.end && batch >= item.start)
                            {
                                isIn = true;
                                order = item.orderCode;
                                break;
                            }
                            size += item.start + "~" + item.end + "\r\n";
                        }
                        if (isIn == false)
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning($"批次号不在区间{size.Trim()}");
                            playerNG.Play();
                            return;
                        }
                        var bind = db2.db.Queryable<out_bind>().First(it => it.batch_code == code.Split(' ')[0]);
                        if (bind != null)
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning($"该批次号已绑定{bind.label_code}！");
                            playerNG.Play();
                            return;
                        }
                        viewModel.Items.Add(new MainViewModel.Item()
                        {
                            No = viewModel.Items.Count + 1,
                            BatchCode = code.Split(' ')[0],
                            MoCode = order,
                            BackColor = Brushes.Gold
                        });
                        TextBoxTitle.Text = "标签号";
                        TextBoxCode.Clear();
                        TextBoxCode.Focus();
                        TextBoxCode.SelectAll();
                        List.ScrollIntoView(List.Items[List.Items.Count - 1]);
                        playerOK.Play();
                    }
                    else if (TextBoxTitle.Text == "标签号")
                    {

                        if (viewModel.Items[viewModel.Items.Count - 1].BackColor != Brushes.Gold)
                        {
                            Growl.Warning($"扫码顺序异常！请重开软件");
                            playerNG.Play();
                            return;
                        }
                        if (!code.StartsWith("20") || !code.Contains("-"))
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning("标签号有误！");
                            playerNG.Play();
                            return;
                        }
                        var str = code.Replace("@", "").Split('-');
                        if (str.Length != 2)
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning("标签号有误！");
                            playerNG.Play();
                            return;
                        }
                        if (!int.TryParse(str[1], out int label))
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning("标签号有误！");
                            playerNG.Play();
                            return;
                        }
                        if (label > end || label < start)
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning($"标签号不在区间{start}~{end}！");
                            playerNG.Play();
                            return;
                        }
                        var bind = db2.db.Queryable<out_bind>().First(it => it.label_code == code);
                        if (bind != null)
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            //Growl.Warning($"标签号已绑定{bind.batch_code}！");
                            playerNG.Play();
                            var mes = HandyControl.Controls.MessageBox.Ask("标签号已绑定" + bind.batch_code + "，确认继续绑定？", "提示");
                            if (mes != MessageBoxResult.OK)
                            {
                                return;
                            }
                        }
                        var a = db2.db.Insertable(new out_bind()
                        {
                            order_code = viewModel.Items[viewModel.Items.Count - 1].MoCode,
                            label_code = code,
                            batch_code = viewModel.Items[viewModel.Items.Count - 1].BatchCode,
                            user = TextBoxName.Text,
                            time = db2.db.GetDate()
                        }).ExecuteCommand();
                        if (a != 1)
                        {
                            TextBoxCode.Focus();
                            TextBoxCode.SelectAll();
                            Growl.Warning($"绑定失败，请重试！");
                            playerNG.Play();
                            return;
                        }
                        viewModel.Items[viewModel.Items.Count - 1].LabelCode = code;
                        viewModel.Items[viewModel.Items.Count - 1].BackColor = Brushes.YellowGreen;
                        TextBoxTitle.Text = "批次号";
                        TextBoxCode.Clear();
                        TextBoxCode.Focus();
                        TextBoxCode.SelectAll();
                        int bindCount = 0;
                        foreach (var item in orders)
                        {
                            bindCount += db2.db.Queryable<out_bind>().Count(it => it.order_code == item.orderCode.Trim());
                        }
                        viewModel.Wait[0] = count - bindCount;
                        viewModel.Pass[0] = bindCount;
                        playerOK.Play();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Error(ex.ToString());
                    return;
                }

            }
        }
        int count;
        int start;
        int end;
        string num;
        List<Order> orders = new List<Order>();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (TextBoxCode.IsEnabled)
                {
                    TextBoxCode.IsEnabled = false;
                    TextBoxName.IsEnabled = true;
                    TextBoxOrder.IsEnabled = true;
                    TextBoxStart.IsEnabled = true;
                    TextBoxEnd.IsEnabled = true;
                    TextBoxName.Text = num;
                    (sender as Button).Content = "确认";
                }
                else if (TextBoxCode.IsEnabled==false)
                {
                    if (TextBoxName.Text == "")
                    {
                        TextBoxName.Focus();
                        TextBoxName.SelectAll();
                        MessageBox.Warning("请输入工号！");
                        return;
                    }
                    var user = db2.GetUser(TextBoxName.Text.Trim());
                    if (user == null)
                    {
                        TextBoxName.Focus();
                        TextBoxName.SelectAll();
                        MessageBox.Warning("未能获取作业人员信息！");
                        return;
                    }
                    num = TextBoxName.Text.Trim();

                    if (TextBoxOrder.Text == "")
                    {
                        TextBoxCode.Focus();
                        TextBoxCode.SelectAll();
                        MessageBox.Warning("请输入订单号！");
                        return;
                    }
                    var orderCodes = TextBoxOrder.Text.Trim().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    List<order_recoder> orderModel = new List<order_recoder>();
                    foreach (var item in orderCodes)
                    {
                        var order = db2.db.Queryable<order_recoder>().First(it => it.order_code == item);
                        if (order == null)
                        {
                            TextBoxOrder.Focus();
                            TextBoxOrder.SelectAll();
                            MessageBox.Warning($"未能获取订单{item}信息！");
                            return;
                        }
                        orderModel.Add(order);
                    }
                    orders.Clear(); 
                    count = 0;
                    foreach (var item in orderModel)
                    {
                        if (!item.batch_code.Contains(",") || !item.batch_code.StartsWith("@"))
                        {
                            TextBoxOrder.Focus();
                            TextBoxOrder.SelectAll();
                            MessageBox.Warning(item.order_code + "批次信息有误！");
                            return;
                        }
                        string[] batchs = item.batch_code.Replace("@", "").Split(',');
                        count += int.Parse(batchs[1]) - int.Parse(batchs[0]) + 1;
                        orders.Add(new Order() { orderCode = item.order_code, start = int.Parse(batchs[0]), end = int.Parse(batchs[1]) });
                    }
                    if (TextBoxStart.Text == "" || !int.TryParse(TextBoxStart.Text, out start))
                    {
                        TextBoxStart.Focus();
                        TextBoxStart.SelectAll();
                        MessageBox.Warning("起始标签输入有误！");
                        return;
                    }
                    if (TextBoxEnd.Text == "" || !int.TryParse(TextBoxEnd.Text, out end))
                    {
                        TextBoxEnd.Focus();
                        TextBoxEnd.SelectAll();
                        MessageBox.Warning("结束标签输入有误！");
                        return;
                    }
                    //if (end - start + 1 != count)
                    //{
                    //    TextBoxStart.Focus();
                    //    TextBoxStart.SelectAll();
                    //    MessageBox.Warning($"标签数量{end - start + 1}与批次数量{count}不一致！");
                    //    return;
                    //}
                    int bindCount = 0;
                    foreach (var item in orders) 
                    {
                        bindCount += db2.db.Queryable<out_bind>().Count(it => it.order_code == item.orderCode.Trim());
                    }
                    viewModel.Wait[0] = count - bindCount;
                    viewModel.Pass[0] = bindCount;
                    TextBoxName.Text = user.username;
                    TextBoxCode.Text = "";
                    TextBoxCode.Focus();
                    TextBoxCode.SelectAll();
                    TextBoxCode.IsEnabled = true;
                    TextBoxName.IsEnabled = false;
                    TextBoxOrder.IsEnabled = false;
                    TextBoxStart.IsEnabled = false;
                    TextBoxEnd.IsEnabled = false;
                    TextBoxTitle.Text = "批次号";
                    viewModel.Items.Clear();
                    (sender as Button).Content = "修改";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Error(ex.ToString());
                return;
            }
        }

        private void Button_Click1(object sender, RoutedEventArgs e)
        {

        }
    }
    public class Order 
    {
        public string orderCode { get; set; }
        public int start { get; set; }
        public int end { get; set; }
    }
}
